package com.zoke.daycarpool.ui;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.umeng.update.UmengUpdateAgent;
import com.zoke.daycarpool.R;
import com.zoke.daycarpool.adapter.MainTabAdapter;
import com.zoke.daycarpool.base.BaseUi;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.CarpoolConfig.MessageCode;
import com.zoke.daycarpool.config.CarpoolConfig.ShareKey;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.domain.Token;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.domain.UserInstense;
import com.zoke.daycarpool.fragment.MainFragment;
import com.zoke.daycarpool.util.LogTest;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeErro;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.utils.MessageHandlerList;
import com.zoke.support.utils.PersistTool;

/**
 * 首页
 * 
 * @author jack
 * 
 */
public class Main extends BaseUi implements OnPageChangeListener,
		AMapLocationListener {
	private ViewPager mViewPager;
	private MainTabAdapter mAdapter;
	private ImageView mTab1Iv;
	private TextView mNotifyTv;
	private int mCurrentPosition;// 默认是第一个
	private TextView mTab1Tv;
	private ImageView mTab2Iv;
	private TextView mTab2Tv;
	private LocationManagerProxy mAMapLocationManager;
	private boolean mDoubleExitMain = false;

	private UserBeen mUser;

	private String mMsgId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mEnableDoubleExit = true;
		mUser = UserInstense.getInstense(getApplicationContext()).getUser();
		mAdapter = new MainTabAdapter(getSupportFragmentManager());
		findView();
		doEvent();
		// 初始化定位--- 高德定位
		mAMapLocationManager = LocationManagerProxy.getInstance(this);
		mAMapLocationManager.requestLocationData(
				LocationProviderProxy.AMapNetwork, -1, 10, this);
		UmengUpdateAgent.update(this);
		mMsgId = PersistTool.getString(CarpoolConfig.MAINTIMESTAMPID, "");
		checkTab2Text();
	}

	@Override
	protected void handleMsg(Message msg) {
		super.handleMsg(msg);
		switch (msg.what) {
		case MessageCode.UPDATE_MIENFRAGMENT:
			mUser = UserInstense.getInstense(getApplicationContext()).getUser();
			checkTab2Text();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		mMsgId = PersistTool.getString(CarpoolConfig.MAINTIMESTAMPID, "");
		if (!TextUtils.isEmpty(mMsgId))
			fetchUnread();
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		String result = (String) out.getResult();
		LogTest.tag("result==" + result);
		/**
		 * result=={"code":"0","msg":"操作成功"
		 * ,"result":0,"sid":"","token":"2854723511239"}
		 **/
		try {
			mNotifyTv.setVisibility(View.GONE);
			JSONObject jo = new JSONObject(result);
			int code = jo.optInt("code");
			if (code == 0) {
				// 成功
				long token = jo.optLong("token");
				Token.getTokener().updateToken(token);
				int count = jo.optInt("result");
				if (count != 0) {
					// 显示 -
					mNotifyTv.setVisibility(View.VISIBLE);
					mNotifyTv.setText("" + count);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeErro erro = (ZokeErro) out.getResult();
		LogTest.tag("erro=" + erro.getErrorNo());
		mNotifyTv.setVisibility(View.GONE);
	}

	/** 获取未读 **/
	private void fetchUnread() {
		ZokeParams param = CarpoolParamStore.getDefaultParam(mHashCode);
		param.setUrl(UrlBank.doUnreadNum);
		param.put("chId", "1");
		param.put("timestamp", "" + mMsgId);
		param.put("sid", "" + mUser.getUserId());
		HttpStores.getInstense(getApplicationContext()).get(param);
	}

	@Override
	protected void findView() {
		mViewPager = (ViewPager) findViewById(R.id._viewPager);
		mViewPager.setCanScroll(false);
		// 设置viewpager保留界面不重新加载的页面数量
		mViewPager.setOffscreenPageLimit(3);
		// 默认是1,，自动预加载左右两边的界面。设置viewpager预加载数为0。只加载加载当前界面。
		mViewPager.setPrepareNumber(0);
		mViewPager.setAdapter(mAdapter);
		mViewPager.setOnPageChangeListener(this);
		findBottom();
	}

	private void checkTab2Text() {
		String identy = mUser.getIdentify().equals("1") ? "我是乘客" : "我是车主";
		mTab2Tv.setText("" + identy);
	}

	/** 处理bttom的view **/
	private void findBottom() {
		// tab1的icon
		mTab1Iv = (ImageView) findViewById(R.id._tab1Icon_iv);
		// tab1上的提醒 一般隐藏
		mNotifyTv = (TextView) findViewById(R.id._notify_numtv);
		// tab1的文本
		mTab1Tv = (TextView) findViewById(R.id._tab1text_tv);
		mTab2Iv = (ImageView) findViewById(R.id._tab2Icon_iv);
		mTab2Tv = (TextView) findViewById(R.id._tab2text_tv);
		setTabSelected(0);
		mNotifyTv.setVisibility(View.GONE);
	}

	// 设置选中状态
	private void setTabSelected(int position) {
		mTab1Iv.setSelected(position == 0);
		mTab1Tv.setSelected(position == 0);
		// 并将tab2置换为
		mTab2Iv.setSelected(position == 1);
		mTab2Tv.setSelected(position == 1);
	}

	/** tab1的点击 **/
	public void onClickMain(View view) {
		if (mViewPager == null)
			return;
		if (mCurrentPosition == 0) {
			// 当前是第一个不需要执行下面的代码 -- 执行刷新逻辑
			onMainDoubleClick();
			return;
		}
		setTabSelected(0);
		mViewPager.setCurrentItem(0, false);
		mCurrentPosition = 0;
	}

	/** tab2的点击 **/
	public void onClickMine(View view) {
		if (mViewPager == null)
			return;
		if (mCurrentPosition == 1) {
			// 当前是第一个不需要执行下面的代码 -- 执行刷新逻辑
			return;
		}
		setTabSelected(1);
		mViewPager.setCurrentItem(1, false);
		mCurrentPosition = 1;
	}

	/** 发布拼车需求 **/
	public void onClickSend(View viwe) {
		mIntent = new Intent(Main.this, Publish.class);
		startUI(mIntent);
	}

	/**
	 * 首页双击两下 进行主动刷新
	 */
	public void onMainDoubleClick() {
		if (mDoubleExitMain) {
			MessageHandlerList.sendMessage(MainFragment.class,
					MessageCode.REUPDATE_MAIN);
			return;
		}
		mDoubleExitMain = true;
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				mDoubleExitMain = false;
			}
		}, 1000);
	}

	@Override
	protected void doEvent() {

	}

	@Override
	public void onPageScrolled(int position, float positionOffset,
			int positionOffsetPixels) {

	}

	@Override
	public void onPageSelected(int position) {

	}

	@Override
	public void onPageScrollStateChanged(int state) {

	}

	@Override
	public void onLocationChanged(Location location) {

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onProviderDisabled(String provider) {

	}

	@Override
	public void onLocationChanged(AMapLocation location) {
		if (location == null)
			return;
		double lat = location.getLatitude();
		double lng = location.getLongitude();
		// -- 存储定位
		if (lat == 0 && lng == 0)
			return;
		PersistTool.saveString(ShareKey.LAT, lat + "");
		PersistTool.saveString(ShareKey.LON, lng + "");
	}
}
